<template>
  <div class="CouponGrant vh100 flc" :style="{ paddingTop: `${45 + statusBarHeight}px` }">
    <NavBar 
      :navBarStyle="{
        backgroundColor: navBarBg,
        height: `${45 + statusBarHeight}px`,
        paddingTop: `${statusBarHeight}px`,
      }"
      pageName="发放优惠券"
      @onLeftClick="leftBack" 
    >
      <!-- <div slot="nav-right" class="fl vc end">
        <img src="@/assets/images/icon_grant.png" class="img24 mr" />
        <img src="@/assets/images/icon_search.png" class="img24" @click="showSearch = !showSearch" />
      </div> -->
    </NavBar>
    <div class="fls wb mb10 grant_header">
      <div class="plr_16 mb10 wb">
        <van-field
          @input="resetSearch"
          v-model.trim="queryParams.storeName"
          left-icon="search"
          placeholder="输入要查询的店铺"
        />
      </div>
      <div class="wb pad_8_16 bg_notice fl vc mb10" @click.stop="show = true">
        <img src="@/assets/images/icon_notice.png" class="img16 fls" />
        <div class="fl1 plr_10" v-if="couponInfo.benefitBatchId">
          <p class="color_333 dx_14">已选：{{ couponInfo.title }}</p>
          <div class="fl vc color_333 dx_14" v-if="couponInfo.benefitBatchType == 10">
            <span class="mr10">本次发放数量/可发放数量</span> 
            <span>{{mathUtil.numberRide(grantNum, checkList.length)}}/{{ totalNum === 0 ? '∞' : usable }}</span>
          </div>
        </div>
        <div class="fl1 plr_10 color_333 dx_14" v-else>请选择优惠</div>
        <img src="@/assets/images/icon_more.png" class="img16 fls" />
      </div>
      <div class="plr_16">
        <van-checkbox @change="handleCheckAllChange" v-model="checkAll" icon-size="20px" checked-color="#D1FB71">批量选择店铺</van-checkbox>
      </div>
    </div>
    <div class="hb flau plr_16 grant_content">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-checkbox-group @change="handleCheckedChange" v-model="checkList">
          <div class="wb mb10 fl vc" style="overflow-x: hidden;" v-for="(item) in storeList" :key="item.storeId">
            <div class="wb">
              <van-checkbox :name="item.storeId" icon-size="20px" checked-color="#D1FB71">
                <div class="wb bg_fff bkra8">
                  <StoreItem :item="item"></StoreItem>
                  <div class="plr_10 pdb_10 fl vc">
                    <div class="fl vc">
                      <img src="@/assets/images/icon_unpower.png" class="img16 mr5 fls" />
                      <p class="dx_14">未授权剧本({{ scriptList.length - item.scriptList.length }})</p>
                    </div>
                    <div class="fl vc ml8">
                      <img src="@/assets/images/icon_power.png" class="img16 mr5 fls" />
                      <p class="dx_14">已授权剧本({{ item.scriptList.length }})</p>
                    </div>
                  </div>
                </div>
              </van-checkbox>
            </div>
          </div>
        </van-checkbox-group>
      </van-list>
    </div>
    <div class="fls pad_16 bg_fff fl vc mt10 grant_footer pdb_40">
      <div class="w_30 flc vc fls">
        <img src="@/assets/images/icon_explain.png" class="img16" />
        <p class="color_333 dx_14">发放数量</p>
      </div>
      <div class="fl1 plr_16">
        <van-field
          :disabled="couponInfo.benefitBatchType == 20"
          type="digit"
          input-align="center"
          v-model.trim="grantNum"
          @input="changeNum"
          placeholder=""
        />
      </div>
      <p class="grant_btn flvcc fls" @click="clickGive">发放优惠券</p>
    </div>

    <van-popup v-model="show" get-container="body" position="bottom">
      <van-picker :columns="batchList" show-toolbar value-key="title" @cancel="show = !show" @confirm="onConfirm"></van-picker>
    </van-popup>
  </div>
</template>

<script>
import NavBar from '@/components/NavBar/NavBar.vue'
import StoreItem from './components/StoreItem.vue'
import { List, Checkbox, CheckboxGroup, Field, Picker, Dialog } from 'vant';
import { Toast } from 'vant';
import { navOtherHeight } from '@/config/config'
import { formatterStatus, fnOmit } from '@/utils/util'
import { getStoreList, issueCouponToStoreList, addBenefitPackageList, selectCouponPage } from '@/api/store.js'
import { getApplyScriptList } from '@/api/script.js'
import mathUtil from '@/utils/mathUtil'

export default {
  components: {
    [List.name]: List,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [Dialog.Component.name]: Dialog.Component,
    [Field.name]: Field,
    [Picker.name]: Picker,
    NavBar,
    StoreItem,
  },

  data() {
    return {
      mathUtil,
      formatterStatus,
      fnOmit,
      navBarBg: 'transparent',
      navigationHeight: 47,
      statusBarHeight: 0,
      navOtherHeight,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeName: ''
      },
      showSearch: false,
      loading: true,
      finished: false,
      storeList: [],
      scriptList: [],
      batchList: [],

      show: false,
      couponInfo: {},
      totalNum: 0,
      usable: 0,

      checkAll: false,
      checkList: [],
      grantNum: ''
    };
  },

  watch: {
    "$store.state.token": {
      handler:function() { 
        this.getStoreList()
        this.getScriptList()
        this.getBatchList()
      }
    }
  },

  created() {
    this.getAPPNavHeight()
    if (this.$store.state.token) {
      this.getStoreList()
      this.getScriptList()
      this.getBatchList()
    }
    const { type } = this.$route.query
    if (type == 1) {
      this.couponInfo = JSON.parse(sessionStorage.getItem('couponInfo'))
    }
  },

  methods: {
    onLoad() {
      console.log('到底')
      this.queryParams.pageNum += 1
      this.getStoreList()
    },
    resetSearch() {
      this.queryParams.pageNum = 1
      this.getStoreList()
    },

    leftBack () {
      // console.log('点击了', window)
      // if (window.androidJSBridge) {
      //   window.androidJSBridge.back()
      // } else if (window.webkit) {
      //   console.log('ios')
      //   window.webkit.messageHandlers.back.postMessage({})
      // }
      this.$router.back()
    },

    getAPPNavHeight () {
      console.log('--appNavigation--', window)
      if (window.androidJSBridge) {
        const result = JSON.parse(window.androidJSBridge.appNavigation())
        this.navigationHeight = result.navigationHeight
        this.statusBarHeight = result.statusBarHeight
        console.log('android1', result)
      } else if (window.webkit) {
        console.log('ios-appNavigation')
        window.appNavigation = this.onAppNavigation
        window.webkit.messageHandlers.appNavigation.postMessage({})
      }
    },

    onAppNavigation (result) {
      console.log('ios--appNavigation', result)
      this.navigationHeight = Number(result.navigationHeight)
      this.statusBarHeight = Number(result.statusBarHeight)
    },

    // 多选店铺
    handleCheckAllChange (val) {
      if (!val && this.checkList.length < this.storeList.length) {
        return
      } else {
        this.checkList = val ? this.storeList.map(item => item.storeId) : []
      }
    },
    handleCheckedChange () {
      const checkedCount = this.checkList.length
      this.checkAll = checkedCount === this.storeList.length
    },

    // 变更发放数量
    changeNum() {
      if (this.totalNum > 0 && mathUtil.numberRide(this.grantNum, this.checkList.length) > this.usable) {
        Toast(`该优惠批次可发数量为${this.usable}张`)
        this.grantNum = parseInt(mathUtil.numberExcept(this.usable, this.checkList.length))
      }
    },
    // 切换优惠
    onConfirm(obj) {
      this.show = false
      console.log(obj)
      this.couponInfo = obj
      if (this.couponInfo.benefitBatchType == 10) {
        const usedNum = this.couponInfo.grantNum || 0
        this.totalNum = this.couponInfo.totalNum || 0
        this.usable = this.couponInfo.totalNum === 0 ? 0 : this.totalNum - usedNum
        if (this.totalNum > 0 && this.grantNum > this.usable) {
          this.grantNum = this.usable
        }
      } else {
        this.grantNum = ''
      }
    },

    // 发放
    clickGive() {
      // const type = this.couponList.find(item => item.benefitBatchId == this.couponInfo).benefitBatchType
      if (!this.couponInfo.benefitBatchId) {
        Toast('请选择优惠')
        return false
      }
      if (this.couponInfo.benefitBatchType == 10 && !this.grantNum) {
        Toast('请输入发放数量')
        return false
      }
      if (this.checkList.length === 0) {
        Toast('请选择要发放的店铺')
        return false
      }
      Dialog.confirm({
        title: '提示',
        message: '确定要发放吗?',
      })
      .then(() => {
        if (this.couponInfo.benefitBatchType == 10) {
          const params = {
            request: {
              couponBatchId: this.couponInfo.benefitBatchId,
              channelSourceType: 0,
              issuanceType: 10,
              receiverUserType: 20,
              issueCount: this.grantNum,
              receiverStoreIds: this.checkList,
            }
          }
          issueCouponToStoreList(params)
            .then((res) => {
              // console.log(res)
              if (res.errorCode == 0) {
                Toast('发放成功')
                this.grantNum = ''
                this.checkList = []
                this.totalNum = 0
                this.usable = 0
                this.couponInfo = {}
                this.$router.back(0)
              }
            })
            .catch(() => {
              // this.$message.info('取消设置!');
            })
        } else {
          const params = {
            request: {
              benefitPackageBatchIds: [this.couponInfo.benefitBatchId],
              channelSourceType: 0,
              issuanceType: 10,
              receiverUserType: 20,
              benefitPackageStatus: 18,
              receiveIds: this.checkList,
            }
          }
          addBenefitPackageList(params)
            .then((res) => {
              // console.log(res)
              if (res.errorCode == 0) {
                Toast('发放成功')
                this.grantNum = ''
                this.checkList = []
                this.totalNum = 0
                this.usable = 0
                this.couponInfo = {}
                this.$router.back(0)
              }
            })
            .catch(() => {
              // this.$message.info('取消设置!');
            })
        }
      })
    },

    // 获取店铺列表
    async getStoreList () {
      try {
        const params = {
          request: {
            dto: {
              ...this.queryParams
            }
          }
        }
        const res = await getStoreList(params)
        console.log('店铺列表', res)
        if (res.errorCode === 0) {
          if (res.response.records.length) {
            this.storeList = this.queryParams.pageNum > 1 ? [...this.storeList, ...res.response.records] : res.response.records
            if (this.checkAll) {
              this.checkList = this.storeList.map(item => item.storeId)
            }
          }
          else {
            this.storeList = this.queryParams.pageNum > 1 ? this.storeList : res.response.records
          }
          if (res.response.records.length < this.queryParams.pageSize) {
            this.finished = true
            this.loading = true
          } else {
            this.finished = false
            this.loading = false
          }
        }
      } catch (error) {
        console.error(error)
      }
    },

    // 获取剧本列表
    async getScriptList () {
      try {
        const params = {
          request: {
            dto: {
            }
          }
        }
        const res = await getApplyScriptList(params)
        console.log('剧本列表', res)
        if (res.errorCode === 0) {
          this.scriptList = res.response.map(item => {
            return {
              id: item.scriptId,
              ...item
            }
          })
        }
      } catch (error) {
        console.error(error)
      }
    },

    // 获取批次列表
    async getBatchList () {
      try {
        const params = {
          request: {
            pageNum: 1,
            pageSize: 100,
            issuanceType: 10,
            isGrant: 0,
            batchStatus: 10
          }
        }
        const res = await selectCouponPage(params)
        console.log('批次列表', res)
        if (res.errorCode === 0) {
          this.batchList = res.response.records
        }
      } catch (error) {
        console.error(error)
      }
    },
  }
};
</script>

<style lang="less">
.CouponGrant {
  
}
.grant_header {
  .van-checkbox__label {
    font-size: 14px;
    margin-left: 6px;
    font-weight: bold;
  }
  .van-cell {
    border-radius: 8px;
  }
}
.grant_content {
  .van-checkbox__label {
    margin-left: 16px;
    width: 100%;
  }
}
.grant_footer {
  .van-cell {
    background: #F3F6F7;
    border-radius: 12px;
  }
}
.pad_8_16 {
  padding: 8px 16px;
}
.pad_12 {
  padding: 12px;
}
.pdl_12 {
  padding-left: 12px;
}

.w_30 {
  width: 30px;
}

.bg_notice {
  background: #FFF7E8;
}

.grant_btn {
  width: 165px;
  height: 48px;
  background: #D1FB71;
  font-size: 16px;
  font-weight: bold;
  border-radius: 16px;
}

</style>
